# -*- coding: utf-8 -*-
import os
import time
from StringIO import StringIO
from accost.middlewares.gzip import GzipMiddleware
############################################################################
__all__ = ['TimeMiddleware', 'ChangeProcessTitleMiddleware',
'ExceptionTemplateMiddleware', 'GzipMiddleware', 'StormSQLMiddleware']


class StormSQLMiddleware(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        try:
            from storm import tracer
        except:
            return self.application(environ, start_response)
        sql_log = StringIO()
        tracer.remove_all_tracers()
        tracer.install_tracer(tracer.DebugTracer(sql_log))
        def new_start_response(status, headers, exc_info=None):
            l = filter(bool, sql_log.getvalue().split("\n"))
            l = filter(lambda log: not log.endswith("DONE"), l)
            for i, log in enumerate(l):
                headers.append(('X-sql-%d'%(i+1,), log))
            return start_response(status, headers, exc_info)
        return self.application(environ, new_start_response)


class TimeMiddleware(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        request_time = time.time()
        def new_start_response(status, headers, exc_info=None):
            t = int((time.time() - request_time) * 1000)
            headers.append(('X-Runtime', str(t)))
            return start_response(status, headers, exc_info)
        return self.application(environ, new_start_response)


class ExceptionTemplateMiddleware(object):
    """need jinja2"""
    def __init__(self, application, status, env, tmpl_name):
        self.application = application
        self.status = status
        self.env = env
        self.tmpl_name = tmpl_name

    def __call__(self, environ, start_response):
        def new_start_response(status, headers, exc_info=None):
            self.real_status = status
            return start_response(status, headers, exc_info)
        result = self.application(environ, new_start_response)
        if self.status == self.real_status:
            return [self.env.get_template(self.tmpl_name).render().encode('utf-8')]
        else:
            return result


if os.name == 'posix':
    try:
        import ctypes
    except ImportError:
        libc = None
    else:
        libc = ctypes.CDLL('/lib/libc.so.6')  
else:
    libc = None
class ChangeProcessTitleMiddleware(object):
    def __init__(self, application):
        self.application = application

    def __call__(self, environ, start_response):
        if environ['wsgi.multiprocess'] and os.name == 'posix':
            procname = environ['PATH_INFO']
            libc.prctl(15, '%s\0'%procname, 0, 0, 0)
        return self.application(environ, start_response)
